// @ts-nocheck

let seed = 1;
function random() {
  const x = Math.sin(seed) * 10000;
  seed += 1;
  return x - Math.floor(x);
}
function uniform(min, max) {
  const r = random();
  return min + r * (max - min);
}
function rbool() {
  return random() > 0.5;
}

let a,
  b,
  c,
  d,
  e,
  t,
  j,
  flip,
  xi,
  yi,
  xn,
  yn,
  vertical,
  offset,
  width,
  height,
  radius;
function first() {
  e = uniform(-j, j);
  next();
}
function next() {
  const flipold = flip;
  flip = rbool();
  a = flip == flipold ? -e : e;
  b = uniform(-j, j);
  c = uniform(-j, j);
  d = uniform(-j, j);
  e = uniform(-j, j);
}
function sl() {
  return vertical ? height / yn : width / xn;
}
function sw() {
  return vertical ? width / xn : height / yn;
}
function ol() {
  return offset + sl() * (vertical ? yi : xi);
}
function ow() {
  return offset + sw() * (vertical ? xi : yi);
}
function l(v) {
  const ret = ol() + sl() * v;
  return Math.round(ret * 100) / 100;
}
function w(v) {
  const ret = ow() + sw() * v * (flip ? -1.0 : 1.0);
  return Math.round(ret * 100) / 100;
}
function p0l() {
  return l(0.0);
}
function p0w() {
  return w(0.0);
}
function p1l() {
  return l(0.2);
}
function p1w() {
  return w(a);
}
function p2l() {
  return l(0.5 + b + d);
}
function p2w() {
  return w(-t + c);
}
function p3l() {
  return l(0.5 - t + b);
}
function p3w() {
  return w(t + c);
}
function p4l() {
  return l(0.5 - 2.0 * t + b - d);
}
function p4w() {
  return w(3.0 * t + c);
}
function p5l() {
  return l(0.5 + 2.0 * t + b - d);
}
function p5w() {
  return w(3.0 * t + c);
}
function p6l() {
  return l(0.5 + t + b);
}
function p6w() {
  return w(t + c);
}
function p7l() {
  return l(0.5 + b + d);
}
function p7w() {
  return w(-t + c);
}
function p8l() {
  return l(0.8);
}
function p8w() {
  return w(e);
}
function p9l() {
  return l(1.0);
}
function p9w() {
  return w(0.0);
}

const h_pathMap = {};
const v_pathMap = {};
function gen_dh() {
  let str = "";
  vertical = 0;

  for (yi = 0; yi < yn + 1; ++yi) {
    xi = 0;
    first();
    let m = "M " + p0l() + "," + p0w() + " ";
    str += "M " + p0l() + "," + p0w() + " ";

    const _pathMap = {};

    h_pathMap[yi] = h_pathMap[yi] || _pathMap;

    // for (; xi < 1; ++xi)
    for (; xi < xn; ++xi) {
      const end = p9l() + "," + p9w();
      const c1 =
        "C " +
        p1l() +
        "," +
        p1w() +
        " " +
        p2l() +
        "," +
        p2w() +
        " " +
        p3l() +
        "," +
        p3w() +
        " ";
      const c2 =
        "C " +
        p4l() +
        "," +
        p4w() +
        " " +
        p5l() +
        "," +
        p5w() +
        " " +
        p6l() +
        "," +
        p6w() +
        " ";
      const c3 =
        "C " +
        p7l() +
        "," +
        p7w() +
        " " +
        p8l() +
        "," +
        p8w() +
        " " +
        end +
        " ";

      if (yi == 0 || yi == yn) {
        str += m + "L" + end;
        _pathMap[xi + 1] = m + "L" + end;
      } else {
        str += c1 + c2 + c3;
        _pathMap[xi + 1] = m + c1 + c2 + c3;
      }

      m = "M " + end + " ";
      next();
    }
  }

  return str;
}

function gen_dv() {
  let str = "";
  vertical = 1;

  for (xi = 0; xi < xn + 1; ++xi) {
    yi = 0;
    first();
    let m = "M " + p0w() + "," + p0l() + " ";
    str += "M " + p0w() + "," + p0l() + " ";

    const _pathMap = {};

    v_pathMap[xi] = v_pathMap[xi] || _pathMap;

    for (; yi < yn; ++yi) {
      const end = p9w() + "," + p9l();
      const c1 =
        "C " +
        p1w() +
        "," +
        p1l() +
        " " +
        p2w() +
        "," +
        p2l() +
        " " +
        p3w() +
        "," +
        p3l() +
        " ";
      const c2 =
        "C " +
        p4w() +
        "," +
        p4l() +
        " " +
        p5w() +
        "," +
        p5l() +
        " " +
        p6w() +
        "," +
        p6l() +
        " ";
      const c3 =
        "C " +
        p7w() +
        "," +
        p7l() +
        " " +
        p8w() +
        "," +
        p8l() +
        " " +
        end +
        " ";

      if (xi == 0 || xi == xn) {
        str += m + "L" + end;
        _pathMap[yi + 1] = m + "L" + end;
      } else {
        str += c1 + c2 + c3;
        _pathMap[yi + 1] = m + c1 + c2 + c3;
      }

      m = "M " + end + " ";
      next();
    }
  }

  return str;
}
function offsetPath(pathData, startX, startY) {
  const dx = -startX;
  const dy = -startY;
  const commands = pathData.split(/([A-Za-z])/).filter(Boolean);
  let newPathData = "";

  for (let i = 0; i < commands.length; i += 2) {
    const command = commands[i];
    const points = commands[i + 1]
      .trim()
      .split(/\s+/)
      .map((v) => v.split(",").map(Number))
      .flat();

    if (command === "M" || command === "L" || command === "C") {
      for (let j = 0; j < points.length; j += 2) {
        points[j] += dx;
        points[j + 1] += dy;
      }
    }

    newPathData += command + points.join(" ");
  }

  return newPathData;
}

function parse_input() {
  seed = 1;
  t = 20 / 200;
  j = 4 / 100;
  xn = 15;
  yn = 10;
}

export function generate(w = 960, h = 600) {
  width = w;
  height = h;
  offset = 0.0;
  parse_input();
  gen_dh();
  gen_dv();
}

export function getPath(h, v) {
  if (!h || !v) return "";

  // 创建一个临时的SVG路径元素来计算包围盒
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  const tempPath = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "path",
  );
  svg.appendChild(tempPath);
  document.body.appendChild(svg);

  let path = "";
  path += h_pathMap[h][v];
  path += h_pathMap[h - 1][v].replace("M", "L");
  path += v_pathMap[v][h].replace("M", "L");
  path += v_pathMap[v - 1][h].replace("M", "L");

  // path = offsetPath(path)
  tempPath.setAttribute("d", path);
  document.body.removeChild(svg);

  return { path, bbox: tempPath.getBBox() };
}

export function getAllPath() {
  // 创建一个临时的SVG路径元素来计算包围盒
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  const tempPath = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "path",
  );
  svg.appendChild(tempPath);
  document.body.appendChild(svg);
  svg.style.position = "absolute";
  svg.style.left = "0";
  svg.style.top = "0";
  svg.style.zIndex = "9999";
  svg.style.overflow = "visible";

  const paths = [];
  for (let h = 1; h < Object.keys(h_pathMap).length; h++) {
    for (let v = 1; v < Object.keys(v_pathMap).length; v++) {
      let path = "";
      path += h_pathMap[h][v];
      path += h_pathMap[h - 1][v].replace("M", "L");
      path += v_pathMap[v][h].replace("M", "L");
      path += v_pathMap[v - 1][h].replace("M", "L");
      // path += "Z";

      tempPath.setAttribute("d", path);
      const bbox = tempPath.getBBox();

      let _path = offsetPath(path, bbox.x, bbox.y);
      _path += "Z";
      if (v === 1 && h === 1) {
        const _tempPath = document.createElementNS(
          "http://www.w3.org/2000/svg",
          "path",
        );
        _tempPath.setAttribute(
          "d",
          `M0 60C10.67 61.02 28.03 67.23 23.05 55.23C18.08 43.23 39.41 43.23 33.72 55.23C28.03 67.23 42.67 58.46 53.33 60L0 0L53.33 0L53.33 0C54.08 12 46.91 29.66 57.57 24.71C68.24 19.76 68.24 43.76 57.57 36.71C46.91 29.66 53.9 48 53.33 60L0 0L0 60L100,100`,
        );
        _tempPath.style.stroke = "red";
        svg.appendChild(_tempPath);
        console.log(_path);
      }
      paths.push({
        path: _path,
        bbox,
        center: [bbox.x + bbox.width / 2, bbox.y + bbox.height / 2],
      });
    }
  }
  // document.body.removeChild(svg);
  return paths;
}

// 在原有代码基础上新增导出功能
export async function exportPuzzlePieces() {
  const paths = getAllPath();

  console.log(paths, "ganninniang");

  // 创建临时Canvas
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d")!;

  // 批量生成图片
  const images = await Promise.all(
    paths.map(async (piece, index) => {
      // 创建SVG数据
      const svgStr = `
      <svg xmlns="http://www.w3.org/2000/svg" 
           viewBox="${piece.bbox.x} ${piece.bbox.y} 
           ${piece.bbox.width} ${piece.bbox.height}">
        <path d="${piece.path}" fill="#fff"/>
      </svg>`;

      // 转换为Blob
      const blob = new Blob([svgStr], { type: "image/svg+xml" });
      const url = URL.createObjectURL(blob);

      // 加载并绘制到Canvas
      await new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
          canvas.width = img.naturalWidth;
          canvas.height = img.naturalHeight;
          ctx.drawImage(img, 0, 0);
          URL.revokeObjectURL(url);
          resolve(null);
        };
        img.src = url;
      });

      // 转换为PNG
      return {
        index,
        data: canvas.toDataURL("image/png"),
      };
    }),
  );
  console.log(images, "images");

  // 使用异步循环下载
  // 批量下载
  // 每个下载都要等待200ms
  // for (let i = 0; i < images.length; i++) {
  //   await new Promise((resolve) => {
  //     const link = document.createElement('a')
  //     link.href = images[i].data
  //     link.download = `piece_${images[i].index}.png`
  //     link.click()
  //     setTimeout(resolve, 200)
  //   })
  // }
}
export async function previewPuzzlePieces() {
  const paths = getAllPath();
  const container = document.createElement("div"); // 创建预览容器
  container.style.display = "grid";
  container.style.gridTemplateColumns = "repeat(auto-fill, minmax(100px, 1fr))";

  await Promise.all(
    paths.map(async (piece, index) => {
      // 创建独立canvas避免尺寸冲突
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d")!;

      // 生成SVG
      const svgStr = `<svg xmlns="http://www.w3.org/2000/svg"
           viewBox="${piece.bbox.x} ${piece.bbox.y} 
           ${piece.bbox.width} ${piece.bbox.height}">
        <path d="${piece.path}" fill="#f0f"/>
      </svg>`;

      // 加载图像
      const img = await loadImage(svgStr);

      // 设置canvas尺寸
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;
      canvas.style.background = "#ccc ";
      ctx.drawImage(img, 0, 0);

      // 添加DOM元素
      const wrapper = document.createElement("div");
      wrapper.innerHTML = `<small>Piece ${index}</small>`;
      wrapper.appendChild(canvas);
      container.appendChild(wrapper);
    }),
  );

  // 添加到页面右下角
  // container.style.position = 'fixed'
  // container.style.right = '20px'
  // container.style.bottom = '20px'
  // container.style.background = 'white'
  // container.style.padding = '10px'
  document.body.appendChild(container);
}

// 辅助函数加载图片
function loadImage(svgStr: string): Promise<HTMLImageElement> {
  return new Promise((resolve) => {
    const blob = new Blob([svgStr], { type: "image/svg+xml" });
    const url = URL.createObjectURL(blob);
    const img = new Image();
    img.onload = () => {
      URL.revokeObjectURL(url);
      resolve(img);
    };
    img.src = url;
  });
}

export function previewSVGPuzzlePieces() {
  const paths = getAllPath();

  // 创建预览容器
  const container = document.createElement("div");
  container.style.cssText = `
    position: fixed;
    right: 20px;
    bottom: 20px;
    max-height: 80vh;
    overflow: auto;
    background: white;
    padding: 10px;
    box-shadow: 0 0 10px rgba(0,0,0,0.2);
    z-index: 9999;
  `;

  // 创建关闭按钮
  const closeBtn = document.createElement("button");
  closeBtn.textContent = "×";
  closeBtn.style.cssText = `
    position: absolute;
    right: 5px;
    top: 5px;
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
  `;
  closeBtn.onclick = () => document.body.removeChild(container);

  // 创建网格布局
  const grid = document.createElement("div");
  grid.style.cssText = `
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
    margin-top: 20px;
  `;

  paths.forEach((piece, index) => {
    // 创建单个拼图块容器
    const wrapper = document.createElement("div");
    wrapper.style.position = "relative";

    // 直接使用原始SVG路径
    const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute(
      "viewBox",
      `${piece.bbox.x} ${piece.bbox.y} 
      ${piece.bbox.width} ${piece.bbox.height}`,
    );
    svg.style.cssText = `
      width: 100%;
      height: auto;
      border: 1px solid #ccc;
      background: #f5f5f5;
    `;

    // 添加路径
    const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
    path.setAttribute("d", piece.path);
    path.setAttribute("fill", "#fff");
    path.setAttribute("stroke", "#999");
    svg.appendChild(path);

    // 添加编号标签
    const label = document.createElement("div");
    label.textContent = `#${index}`;
    label.style.cssText = `
      position: absolute;
      top: 2px;
      left: 2px;
      font-size: 10px;
      background: rgba(255,255,255,0.8);
      padding: 2px;
    `;

    wrapper.appendChild(svg);
    wrapper.appendChild(label);
    grid.appendChild(wrapper);
  });

  container.appendChild(closeBtn);
  container.appendChild(grid);
  document.body.appendChild(container);
}
